package com.njtoyo.taxi.admin.library.common.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashMap;
import java.util.Map;

public class DownloadUtil {

    /**
     * 下载远程文件并保存到本地
     *
     * @param remoteFilePath-远程文件路径
     * @param localFilePath-本地文件路径（带文件名）
     */
    public static void downloadNetworkFile(String remoteFilePath, String localFilePath) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", -1);
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try {
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 小试牛刀
     *
     * @param args
     */
    public static void main(String[] args) {
        /*远程文件路径*/
        String remoteFilePath1 = "https://s3gw.cmburl.cn:8443/s/L2x3MTNwbXMtYmlsbC11YXQtUE1TRFRCMDIvREFJTFlfSlBfMzA4OTk5MTcyNzMwMTZSXzIwMjMxMDE5Lnhsc3g_QVdTQWNjZXNzS2V5SWQ9bHcxM3Btcy1kdGJ1c2VyLXVhdCZFeHBpcmVzPTE3NDA5NjY5MzgmU2lnbmF0dXJlPW8lMkI2alhrJTJGZUF0Yzd3N0lTbkVISmVRT09tcFElM0QmcmVzcG9uc2UtY29udGVudC1kaXNwb3NpdGlvbj1hdHRhY2htZW50JTNCZmlsZW5hbWUlM0REQUlMWV9KUF8zMDg5OTkxNzI3MzAxNlJfMjAyMzEwMTkueGxzeCUzQmZpbGVuYW1lKiUzRFVURi04JTI3JTI3REFJTFlfSlBfMzA4OTk5MTcyNzMwMTZSXzIwMjMxMDE5Lnhsc3g=/XZStYYhvrNEJnjHgOWBBXveSbDM=/lw13pms-dtbuser-uat-dmz/0";
        /*本地文件路径（带文件名）*/
        String localFilePath1 = "/Users/saber/Desktop/有滴资料/test.xls";
        downloadNetworkFile(remoteFilePath1, localFilePath1);
    }

}
